package com.appwx.sdk.view;



import com.appwx.sdk.R;
import com.appwx.sdk.app.AppLoger;
import com.appwx.sdk.http.Utility;
import com.appwx.sdk.model.OpenApiModel;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.http.SslError;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

/**
 * 
 * @author xiajun
 *
 */
public class WeiboDialog extends Dialog {
	static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
			ViewGroup.LayoutParams.FILL_PARENT);
	static final int MARGIN = 4;
	static final int PADDING = 2;

	private final OpenApiModel mOpenApiModel;
	private String mUrl;
	private WeiboDialogListener mListener;
	private ProgressDialog mSpinner;
	private ImageView mBtnClose;
	private WebView mWebView;
	private LinearLayout webViewContainer;
	private RelativeLayout mContent;

	private final static String TAG = WeiboDialog.class.getSimpleName();
	
	public WeiboDialog(final OpenApiModel openApiModel, Context context, String url, WeiboDialogListener listener) {
		super(context, R.style.ContentOverlay);
		mOpenApiModel = openApiModel;
		mUrl = url;
		mListener = listener;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mSpinner = new ProgressDialog(getContext());
		mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mContent = new RelativeLayout(getContext());
		if (android.os.Build.VERSION.SDK_INT > 9) {
			// StrictMode.ThreadPolicy policy =
			// new StrictMode.ThreadPolicy.Builder().permitAll().build();
			// StrictMode.setThreadPolicy(policy);
		}
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
	                | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		setUpWebView();

		// setUpCloseBtn();

		addContentView(mContent, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
	}

	private void setUpWebView() {
		webViewContainer = new LinearLayout(getContext());
		// webViewContainer.setOrientation(LinearLayout.VERTICAL);

		// webViewContainer.addView(title, new
		// LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
		// getContext().getResources().getDimensionPixelSize(R.dimen.dialog_title_height)));

		mWebView = new WebView(getContext());
		mWebView.setVerticalScrollBarEnabled(false);
		mWebView.setHorizontalScrollBarEnabled(false);
		mWebView.setLayoutParams(FILL);
		mWebView.setVisibility(View.INVISIBLE);

		webViewContainer.addView(mWebView);
		mWebView.setInitialScale(100);
		mWebView.setVerticalScrollBarEnabled(false);
		mWebView.setWebViewClient(new WeiboDialog.WeiboWebViewClient());
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.getSettings().setBuiltInZoomControls(true);
		CookieSyncManager.createInstance(getContext());   
		CookieManager cookieManager = CookieManager.getInstance();  
		cookieManager.removeAllCookie(); 
		mWebView.setWebChromeClient(new MyWebChromeClient());
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT);
		Resources resources = getContext().getResources();
//		if (mOpenApiModel.getApp_type() != SnsModel.TYPE_TX) {
//			lp.leftMargin = resources.getDimensionPixelSize(R.dimen.dialog_left_margin);
//			lp.topMargin = resources.getDimensionPixelSize(R.dimen.dialog_top_margin);
//			lp.rightMargin = resources.getDimensionPixelSize(R.dimen.dialog_right_margin);
//			lp.bottomMargin = resources.getDimensionPixelSize(R.dimen.dialog_bottom_margin);
//		} else {
//		}
		getWindow().setBackgroundDrawable(null);
		mContent.addView(webViewContainer, lp);
		mWebView.loadUrl(mUrl);
	}

	private class MyWebChromeClient extends WebChromeClient {

		@Override
		public void onReceivedTitle(WebView view, String title) {
			super.onReceivedTitle(view, title);
			// setWinTitle(title);
		}
	}

	/*--此方法sdk没用到--*/
	private void setUpCloseBtn() {
		mBtnClose = new ImageView(getContext());
		mBtnClose.setClickable(true);
		mBtnClose.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mListener.onCancel();
				WeiboDialog.this.dismiss();
			}
		});

		mBtnClose.setImageResource(R.drawable.close_selector);
		mBtnClose.setVisibility(View.INVISIBLE);

		RelativeLayout.LayoutParams closeBtnRL = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		closeBtnRL.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
		closeBtnRL.addRule(RelativeLayout.ALIGN_PARENT_TOP);
		closeBtnRL.topMargin = getContext().getResources().getDimensionPixelSize(R.dimen.dialog_btn_close_right_margin);
		closeBtnRL.rightMargin = getContext().getResources().getDimensionPixelSize(R.dimen.dialog_btn_close_top_margin);

		webViewContainer.addView(mBtnClose, closeBtnRL);
	}

	private class WeiboWebViewClient extends WebViewClient {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			Log.d(TAG, "Redirect URL: " + url);
			// 待后台增加对默认重定向地址的支持后修改下面的逻辑
			switch (mOpenApiModel.getApp_type()) {
			case OpenApiModel.TYPE_SINA_WEIBO:
				AppLoger.info(TAG,"授权新浪微博");
				break;
			case OpenApiModel.TYPE_TX_WEIBO:
				AppLoger.info(TAG,"授权腾讯微博");
				break;
			case OpenApiModel.TYPE_TX_QQ:
				AppLoger.info(TAG,"授权腾讯QQ登录");
				break;
			case OpenApiModel.TYPE_RENREN:
				AppLoger.info(TAG,"授权人人网");
				break;
			case OpenApiModel.TYPE_KAIXIN:
				AppLoger.info(TAG,"授权开心网");
				break;
			case OpenApiModel.TYPE_BAIDU:
				AppLoger.info(TAG, "授权百度");
				break;
			default:
				break;
			}
			if (url.startsWith(mOpenApiModel.getRedirectUrl())) {
				handleRedirectUrl(view, url);
				WeiboDialog.this.dismiss();
				return true;
			}
			//跳转浏览器
			// getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
			return false;
		}

		@Override
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			mListener.onError(new WeiboError(description, errorCode, failingUrl));
			WeiboDialog.this.dismiss();
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			Log.d(TAG, "onPageStarted URL: " + url);
			// google issue. shouldOverrideUrlLoading not executed
			if (url.startsWith(mOpenApiModel.getRedirectUrl())) {
				handleRedirectUrl(view, url);
				view.stopLoading();
				WeiboDialog.this.dismiss();
				return;
			}
			super.onPageStarted(view, url, favicon);
			mSpinner.show();
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			Log.d(TAG, "onPageFinished URL: " + url);
			super.onPageFinished(view, url);
			mSpinner.dismiss();

			mContent.setBackgroundColor(Color.TRANSPARENT);
//			webViewContainer.setBackgroundResource(R.drawable.dialog_bg1);
			// mBtnClose.setVisibility(View.VISIBLE);
			mWebView.setVisibility(View.VISIBLE);
		}

		public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
			handler.proceed();
		}
	}

	/**
	 * 处理重定向过来的结果
	 * 如http://www.myurl.com/example#access_token=ACCESS_TOKEN&expires_in=60&openid=OPENID&openkey=OPENKEY
	 * @param view
	 * @param url
	 */
	private void handleRedirectUrl(WebView view, String url) {
		Bundle values = Utility.parseUrl(url);
		String error = values.getString("error");
		String error_code = values.getString("error_code");

		if (TextUtils.isEmpty(error) && TextUtils.isEmpty(error_code)) {
			if (mOpenApiModel.getApp_type() == OpenApiModel.TYPE_TX_WEIBO) {
//				AppLoger.info(TAG, "token =" + values.getString(OpenApiModel.TOKEN) + "&expires_in=" + values.getString(OpenApiModel.EXPIRES));
//				mOpenApiModel.getAccessToken().setToken(values.getString(OpenApiModel.TOKEN));
//				mOpenApiModel.getAccessToken().setExpiresIn(values.getString(OpenApiModel.EXPIRES));
//				mOpenApiModel.getAccessToken().setOpenId(values.getString(OpenApiModel.OPENID));
//				mOpenApiModel.getAccessToken().setRefreshToken(values.getString(OpenApiModel.REFRESHTOKEN));
				mListener.onComplete(values);
			} else if(mOpenApiModel.getApp_type() == OpenApiModel.TYPE_TX_QQ){
				mListener.onComplete(values);
			}else if (mOpenApiModel.getApp_type() == OpenApiModel.TYPE_SINA_WEIBO) {
				mListener.onComplete(values);
			} else if (mOpenApiModel.getApp_type() == OpenApiModel.TYPE_RENREN) {
				mListener.onComplete(values);
			}else if(mOpenApiModel.getApp_type() == OpenApiModel.TYPE_KAIXIN){
				mListener.onComplete(values);
			}else if(mOpenApiModel.getApp_type() == OpenApiModel.TYPE_BAIDU){
				mListener.onComplete(values);
			}
		} else if (error.equals("access_denied")) {
			// 用户或授权服务器拒绝授予数据访问权限
			mListener.onCancel();
		} else {
			if (!TextUtils.isEmpty(error_code)) {
				mListener.onWeiboException(new WeiboException(error, Integer.parseInt(error_code)));
			}
		}
	}
}
